// common/goods_sku/goodsku.js
import {fetchGoodsInfo} from "../../api/add_shopCar.js"
let app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShow: {
      type: Boolean
    },
    goodsInfo: {
      type: Object,
      default: {}
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    goods_num: 1
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 关闭sku
    onClose() {
      let boolean = !this.data.isShow
      this.triggerEvent('myevent', boolean)
    },
    // 获取步进器绑定值
    fetchGoodsNum(e) {
      this.setData({
        goods_num: e.detail
      })
    },
    async addShopcar(){
      let {errCode:state} = await this.clickLogin();
      if(state != 0) {
        return;
      }
      let goods_num = this.data.goods_num
      let goods_id = this.data.goodsInfo.goods_id
      let goods_id_alias = this.data.goodsInfo.goods_id_alias
      let result = await fetchGoodsInfo(goods_id,goods_num,goods_id_alias)

      let {errCode} = result
      if(errCode === 0){
        wx.showToast({
          title: '加入购物车成功',
          duration:1000,
          success: (res) => {
            // 步进器重置
            let num = 1
            this.setData({
              goods_num:num
            })
            let boolean = !this.data.isShow
            this.triggerEvent('myevent', boolean)
            this.triggerEvent('addSucces', {errCode:true,message:'添加成功'})
          },
        })
      }      
    },
    async ToOrderCommit(e){
      let {errCode} = await this.clickLogin();
      if(errCode != 0) {
        return;
      }
      let num = this.data.goods_num
      let alias = e.currentTarget.dataset.alias
      let data = JSON.stringify([{
        num,
        alias
      }])
      wx.navigateTo({
        url: '/pages/orderCommit/order?goodsId=' + data,
      })
      let boolean = !this.data.isShow
      this.triggerEvent('myevent', boolean)
    },
    // 验证登录
    clickLogin() {
      return new Promise(async (resolve,reject)=>{
        if(!app.globalData.verifyLogin) {
          let {errCode} = await app.login();
          if(errCode == 0) {
            resolve({errCode})
          }
        }else{
          resolve({errCode:0});
        }
      })
    },
  }
})